package httpUtils

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
)

func Post(url string, obj interface{}, resPtr interface{}) error {
	jsonBytes, err := json.Marshal(obj)
	if err != nil {
		return err
	}
	request, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes))
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("token", "BaseServiceadmin")
	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		return err
	}
	//serverDate := resp.Header.Get("date")
	//now, err := time.ParseInLocation(http.TimeFormat, serverDate, time.Local)
	//now = now.Add(time.Hour * 8)
	//fmt.Println(now)

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	var jsonObj map[string]interface{}
	err = json.Unmarshal(body, &jsonObj)
	if err != nil {
		return err
	}
	if resPtr == nil {
		return nil
	}
	bytes, _ := json.Marshal(jsonObj["content"])
	err = json.Unmarshal(bytes, resPtr)
	return err
}

func Get(url string, resPtr interface{}) error {
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("token", "BaseServiceadmin")
	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		return err
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	var jsonObj map[string]interface{}
	err = json.Unmarshal(body, &jsonObj)
	if err != nil {
		return err
	}
	bytes, _ := json.Marshal(jsonObj["content"])
	err = json.Unmarshal(bytes, resPtr)
	return err
}
